package com.histone.lib_download;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.util.Log;

import androidx.core.content.FileProvider;

import com.histone.lib_download.contract.DownloadTakeNotes;
import com.histone.lib_download.downloader.DownloadService;
import com.histone.lib_download.downloader.FileInfo;
import com.histone.lib_download.localbroadcast.LocalBroadcastHolder;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author robin
 * @version v1.0 [2020/6/10]
 * <p>
 * 工厂类*便捷静态工具类 计算、逻辑、格式化
 */
public class DownloadFactory {
    private static final DownloadFactory instance;
    //线程池（自动管理线程，避免多余开支）
    private final ExecutorService executor;

    public DownloadFactory() {
        executor = Executors.newFixedThreadPool(20);
    }

    static {
        instance = new DownloadFactory();
    }

    /**
     * 异步
     *
     * @param runnable
     */
    public static void runOnAsync(Runnable runnable) {
        instance.executor.execute(runnable);
    }

    /**
     * 检测是否存在未完成的下载
     * 建议在启动后 与 网络发生变化后调用
     */
    public static void checkDownload(Context context) {
        boolean shared = DownloadTakeNotes.getInstance().initShared(context);
        if (shared) {
            FileInfo info = new FileInfo(DownloadTakeNotes.getInstance().downloadUrl, DownloadTakeNotes.getInstance().filePath
                    , DownloadTakeNotes.getInstance().fileName, DownloadTakeNotes.getInstance().fileLength, DownloadTakeNotes.getInstance().downloadLength);
            info.finishLength = getFileLength(info.localFilePath, info.fileName);
            if (info.fileLength == info.finishLength) {
                DownloadTakeNotes.getInstance().clean();
                Log.e("DownloadService", "已下载完");
                Intent intent = new Intent(LocalBroadcastHolder.LOCAL_BROADCAST_ACTION);
                intent.putExtra(LocalBroadcastHolder.BROADCAST_CODE, LocalBroadcastHolder.CODE_OK);
                intent.putExtra(LocalBroadcastHolder.BROADCAST_FILE_INFO, info);
                LocalBroadcastHolder.getInstance().sendBroadcast(context, intent);
                return;
            }
            Intent intent = new Intent(context, DownloadService.class);
            intent.setAction(DownloadService.DOWNLOAD_START);
            intent.putExtra(DownloadService.KEY_FILE_INFO, info);
            intent.putExtra(DownloadService.KEY_CHECK_SPACE, true);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(intent);
            } else {
                context.startService(intent);
            }
        } else {
            Log.e("DownloadService", "没有存在的...");
        }
    }

    /**
     * attachment; filename=com.kiloo.subwaysurf_40210.apk
     */
    public static String checkFileName(String fileName) {
        if (!TextUtils.isEmpty(fileName)) {
            String[] split = fileName.split(";");
            for (String s : split) {
                if (!TextUtils.isEmpty(s) && s.contains("filename")) {
                    return s.substring(s.lastIndexOf("=") + 1).replace("\\", "");
                }
            }
        }
        return null;
    }

    public static long getFileLength(String path, String fileName) {
        File file = new File(path, fileName);
        if (file.exists() && file.isFile()) {
            return file.length();
        }
        return 0;
    }

    /**
     * 默认路径
     */
    public static String getDefaultFile() {
        return Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/" + getDate();
    }

    public static String getDate() {
        long timeMillis = System.currentTimeMillis();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
        return dateFormat.format(new Date(timeMillis));
    }

    /**
     * sd卡可用空间*GB
     */
    public static String getFreeSpace(Context context) {
        File sdFile = Environment.getExternalStorageDirectory();
        StatFs statFs = new StatFs(sdFile.getPath());
        long blockSizeLong = statFs.getBlockSizeLong();
        long blockCountLong = statFs.getBlockCountLong();
        long availableBlocksLong = statFs.getAvailableBlocksLong();
        return Formatter.formatFileSize(context, availableBlocksLong * blockSizeLong);
    }

    public static long getFreeSpaceLength(Context context) {
        File sdFile = Environment.getExternalStorageDirectory();
        StatFs statFs = new StatFs(sdFile.getPath());
        long blockSizeLong = statFs.getBlockSizeLong();
        long blockCountLong = statFs.getBlockCountLong();
        long availableBlocksLong = statFs.getAvailableBlocksLong();
        return (availableBlocksLong * blockSizeLong);
    }

    /**
     * 从下载的路径中截取 file name
     *
     * @param url String
     * @return String
     */
    public static String urlName(String url) {
        if (url == null) return null;
        int indexOf = url.lastIndexOf("/");
        return url.substring(indexOf + 1);
    }

    public static void initApk(Context context, File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri fileUri;

        //Android7.0以上
        if (Build.VERSION.SDK_INT >= 24) {
            fileUri = FileProvider.getUriForFile(context,
                    context.getPackageName() + ".provider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            fileUri = Uri.fromFile(file);
        }

        intent.setDataAndType(fileUri, "application/vnd.android.package-archive");
        context.startActivity(intent);
    }


}
